package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //对象转换
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        //判断请求路径是否可以放行
        boolean contains = req.getRequestURI().contains("/login");
        if (contains){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        //获取令牌
        String jwt = req.getHeader("token");
        //解析令牌
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            Result error = Result.error("NOT_LOGIN");
            resp.getWriter().write(JSON.toJSONString(error));
            return;
        }
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
